package com.zsh.json;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zsh.pojo.Person;
import org.junit.Test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JsonTest {


    // Javabean 与 JSON
    @Test
    public void test1(){
        Person person = new Person(1,"zsh");

        Gson gson = new Gson();

        String jsonStr = gson.toJson(person);

        System.out.println(jsonStr);

        Person person1 = gson.fromJson(jsonStr, Person.class);

        System.out.println(person1);
    }

    //List 转 json
    @Test
    public void test2(){
        List<Person> personList = new ArrayList<Person>();

        personList.add(new Person(1,"zsh1"));
        personList.add(new Person(2,"zsh2"));

        Gson gson = new Gson();
        String jsonStr = gson.toJson(personList);

        System.out.println(jsonStr);

        List<Person> json2 = gson.fromJson(jsonStr, new PeronListType().getType());

        System.out.println(json2.get(0));
    }

    //map json

    @Test
    public void test3(){
        Map<Integer,Person> personMap = new HashMap<Integer,Person>();

        personMap.put(1,new Person(1,"zsh1"));
        personMap.put(2,new Person(2,"zsh2"));

        Gson gson =new Gson();
        String jsonStr = gson.toJson(personMap);
        System.out.println(jsonStr);

//        Map<Integer,Person> personMap2 = gson.fromJson(jsonStr, new PersonMapType().getType());
        //匿名内部类
        Map<Integer,Person> personMap2 = gson.fromJson(jsonStr, new TypeToken<HashMap<Integer,Person>>(){}.getType());
        System.out.println(personMap2);
    }
}
